<template>
  <Card :bordered="false">
    <p slot="title">
      <Icon type="md-trophy"></Icon>
      部署管理
    </p>
    <a href="#" v-if="permission.deployment_create==='1'" slot="extra" @click.prevent="createView">
      <Icon type="md-add-circle"></Icon>
      创建
    </a>
    <Modal v-model="createModal" draggable scrollable title="创建部署" :footer-hide=true>
      <Form ref="createformValidate" :model="createformValidate" :rules="rulecreateValidate" :label-width="80">
        <FormItem label="云平台" prop="cloud_name">
          <Select v-model="createformValidate.cloud_name">
            <Option v-for="item in cloud_list" :value="item.value" :key="item.value">{{ item.label }}</Option>
          </Select>
        </FormItem>
        <FormItem label="项目名称" prop="name">
          <Input v-model="createformValidate.name" placeholder="请输入项目名称"></Input>
        </FormItem>
        <FormItem label="命名空间" prop="namespace">
          <Select v-model="createformValidate.namespace" placeholder="请选择对应的命名空间">
            <Option v-for="item in namespaced" :key="item.value" :value="item.value">{{item.label}}</Option>
          </Select>
        </FormItem>
        <FormItem label="项目端口" prop="port">
          <Input v-model="createformValidate.port" placeholder="请输入你的服务端口"></Input>
        </FormItem>
        <FormItem label="项目标签" prop="tag">
          <Input v-model="createformValidate.tag" placeholder="请输入镜像标签"></Input>
        </FormItem>
        <FormItem label="副本数量" prop="replicas">
          <Input v-model="createformValidate.replicas" placeholder="请输入服务运行的副本数量"></Input>
        </FormItem>
        <FormItem label="配置域名">
          <i-switch v-model="createformValidate.switch" size="large">
              <span slot="open">On</span>
              <span slot="close">Off</span>
          </i-switch>
        </FormItem>
        <FormItem v-if="createformValidate.switch" label="域名地址" prop="domain">
          <Input v-model="createformValidate.domain" placeholder="请输入你的域名"></Input>
        </FormItem>
        <FormItem>
          <Button type="success" @click="createApplication('createformValidate')">点击提交</Button>
          <Button type="warning" @click="createformReset('createformValidate')" style="margin-left: 8px">清空表单</Button>
          <Button type="info" @click="createModal=false" style="margin-left: 8px">关闭表单</Button>
        </FormItem>
      </Form>
    </Modal>
    <!-- <div style="padding-bottom: 10px;">
      <Row :gutter="16">
        <Col span="10">
          <Select v-model="file_type" style="width:240px;padding-right:10px" placeholder="请选择文件类型" clearable @on-change="handFileList" ref="file_type_select">
            <Option v-for="item in selec_env_men" :value="item.value" :key="item.value">{{ item.label }}</Option>
          </Select>
        </Col>
        <Col span="6" offset="8">
          <Input search placeholder="Search ..." v-model="searchValue" @on-search=searchFile />
        </Col>
      </Row>
    </div> -->
    <div style="padding-bottom: 10px;">
      <Row :gutter="24">
        <Col span="4">
          <Select v-model="cloud_name"  placeholder="请选择云平台" @on-change="GetCloudNamespaces">
            <Option v-for="item in cloud_list" :value="item.value" :key="item.value">{{ item.label }}</Option>
          </Select>
        </Col>
        <Col span="4">
          <Select v-model="namespace"  placeholder="请选择命名空间" clearable @on-change="deploymentData" ref="deployments_list">
            <Option v-for="item in namespaced" :value="item.value" :key="item.value">{{ item.label }}</Option>
          </Select>
        </Col>
        <Col span="4" offset="12">
          <Input search placeholder="Search ..." v-model="search_value" @on-search=searchDeployment />
        </Col>
      </Row>
    </div>
    <Table border :loading="loading" :columns="columns" :data="data">
      <template slot-scope="{ row, index }" slot="status">
        <span v-if="`${row.status}`=='false'" style="color:#ed4014">运行异常</span>
        <span v-else style="color:#19be6b">正在运行</span>
      </template>
      <template slot-scope="{ row, index }" slot="action">
        <Button v-if="permission.deployment_deploy === '1'" type="info" size="small" @click="deploying(index)">更新</Button>
        <Button v-if="permission.deployment_backend === '1'" type="success" size="small" @click="rollBack_view(index)" style="margin-left:5px">回滚</Button>
        <Button v-if="permission.deployment_delete === '1'" type="warning" size="small" @click="updateEdit(index)" style="margin-left:5px">修改</Button>
        <Button v-if="permission.deployment_delete === '1'" type="error" size="small" @click="remove(index)" style="margin-left:5px">删除</Button>
        <span style="color:#ed4014" v-if="permission.deployment_deploy !== '1'&&permission.deployment_backend !== '1'&&permission.deployment_delete !== '1'">无权限</span>
      </template>
    </Table>
    <Modal v-model="rollBackModal" draggable scrollable title="版本回滚" :footer-hide=true>
      <Form ref="formValidate" :model="formValidate" :rules="ruleValidate" :label-width="80">
        <FormItem label="项目名称" prop="name">
          <Input disabled v-model="formValidate.name" placeholder="Enter your project name"></Input>
        </FormItem>
        <FormItem label="历史版本" prop="version">
          <Select v-model="formValidate.version" placeholder="Select your image version">
            <Option v-for="item in history_tag" :key="item.value" :value="item.value">{{item.label}}</Option>
          </Select>
        </FormItem>
        <FormItem>
          <Button type="success" @click="rollBack('formValidate')">点击提交</Button>
          <Button type="info" @click="rollBackModal=false" style="margin-left: 8px">关闭</Button>
        </FormItem>
      </Form>
    </Modal>
    <div style="padding-top: 10px;" v-if="count">
      <template>
        <Page :total="count" show-total :page-size-opts="[10,25,40,55,70,100]" current.sync="current" show-elevator show-sizer @on-change="switchPage" @on-page-size-change="switchPageSize" />
      </template>
    </div>
  </Card>
</template>

<script>
import { namespaceList, deploymentList, deploymentUpdate, deploymentRollBack, deploymentRollBackList, deploymentAllSearch, deploymentDelete, deploymentCreate } from '@/api/production'

  export default {
    data () {
      return {
        loading: false,
        count: '',
        page: 1,
        pageSize: 10,
        search_value: '',
        createModal: false,
        rollBackModal: false,
        // deployment_port: '',
        namespace: '',
        namespaced: [],
        history_tag: [],
        createformValidate: {
          cloud_name: '',
          name: '',
          namespace: '',
          port: '',
          tag: '',
          replicas: '1',
          switch: false,
          domain: ''
        },
        rulecreateValidate: {
          cloud_name: [
            { required: true, message: '云平台名称不能为空', trigger: 'blur' }
          ],
          name: [
            { required: true, message: 'deployment名称不能为空', trigger: 'blur' }
          ],
          namespace: [
            { required: true, message: '命名空间不能为空', trigger: 'blur' }
          ],
          port: [
            { required: true, message: '项目端口不能为空', trigger: 'blur' }
          ],
          tag: [
            { required: true, message: '镜像标签不能为空', trigger: 'blur' }
          ]
        },
        formValidate: {
          name: '',
          version: ''
        },
        ruleValidate: {
          name: [
            { required: true, message: 'The name cannot be empty', trigger: 'blur' }
          ],
          version: [
            { required: true, message: 'The version cannot be empty', trigger: 'blur' }
          ]
        },
        cloud_name: '',
        cloud_list: [
          {value: 'aliyun', label: '阿里云集群'},
          // {value: 'aws-stg', label: 'AWS-STG'},
          // {value: 'aws-prod', label: 'AWS-PROD'}
        ],
        columns: [
          {
            title: '名称',
            key: 'name'
          },
          {
            title: '状态',
            key: 'status',
            slot: 'status'
          },
          {
            title: '副本数',
            key: 'replicas'
          },
          {
            title: '镜像版本',
            key: 'tag'
          },
          {
            title: '创建日期',
            key: 'create_time'
          },
          {
            title: '更新时间',
            key: 'update_time'
          },
          {
            title: '操作',
            slot: 'action',
            width: 230,
            align: 'center'
          }
        ],
        data: [],
        permission: ''
      }
    },
    methods: {
      // 获取用户操作权限
      get_permission () {
        const auth = JSON.parse(sessionStorage.getItem('permission'))
        this.permission = auth.child
      },
      createView () {
        this.createModal = true;
        this.$refs['createformValidate'].resetFields();
      },
      createformReset (name) {
        this.$refs[name].resetFields();
      },
      createApplication (name) {
        this.$refs[name].validate((valid) => {
          if (valid) {
            // 请求后端接口进行回滚
            deploymentCreate(this.createformValidate).then(res => {
              console.log(res)
              this.$Message.success({content:'创建成功!',duration: 5,closable: true})
            }).catch(err => {
              this.$Message.error({content:'创建失败!',duration: 5,closable: true})
            })
          }
        })
      },
      GetCloudNamespaces () {
        this.$refs.deployments_list.clearSingleSelect();
        this.namespaced = [];
        this.data = [];
        this.count = 0;
        this.namespace_list({'cloud_name': this.cloud_name})
      },
      // 获取数据
      namespace_list (cloud) {
        namespaceList(cloud).then(res => {
          var namespace_res = res.data.results
          for (const namespace in namespace_res) {
            if (namespace_res[namespace]['name']==='prod' || namespace_res[namespace]['name']==='stg') {
              var auth = this.permission[`production_${namespace_res[namespace]['name']}_view`]
              if (auth==='1') {
                var select_men = {
                  'value': namespace_res[namespace]['name'],
                  'label': namespace_res[namespace]['name']
                }
                this.namespaced.push(select_men)
              }
            } else {
              var select_men = {
                'value': namespace_res[namespace]['name'],
                'label': namespace_res[namespace]['name']
              }
              this.namespaced.push(select_men)
            }
          }
        })
      },
      //获取数据
      deploymentData (CronStatus) {
        if (this.cloud_name.length !== 0 && this.namespace !== undefined) {
          if (CronStatus === true) {
            this.loading = false;
          } else {
            this.loading = true;
          }
          if (this.search_value.length!==0 && this.count<10){
            this.page = 1;
            this.pageSize = 10;
          }
          var params = {
            'cloud_name': this.cloud_name,
            'namespace_name': this.namespace,
            'Page': this.page,
            'PageSize': this.pageSize,
            'searchName': this.search_value
          }
          if (this.namespace.length !=0 ) {
            deploymentList(params).then(res => {
              this.loading = false;
              this.count = res.data.count
              this.data = res.data.results
            }).catch(err => {
              this.$Message.error("列表获取失败!")
            })
          }
        }
      },
      // 获取页码并发起请求
      switchPage (page) {
        this.page = page
        this.deploymentData()
      },
      // 获取选择切换的每页条数并发起请求
      switchPageSize (pageSize) {
        this.page = 1
        this.pageSize = pageSize
        this.deploymentData()
      },
      // 搜索
      searchDeployment () {
        this.loading = true;
        if (this.namespace.length !=0 ) {
          deploymentAllSearch(this.cloud_name, this.namespace, this.search_value).then(res => {
            this.loading = false;
            this.count = res.data.count
            this.data = res.data.results
          }).catch(err => {
            this.$Message.error('接口请求失败!')
          })
        } else {
          this.$Message.error("请选择应用环境!")
        }
      },
      // 发布
      deploying (index) {
        this.$Modal.confirm({
          title: "警告!",
          content: `<p>将${this.data[index].name}的镜像版本更到最新，是否继续？</p>`,
          onOk: () => {
            var params = {
              'cloud_name': this.cloud_name,
              'namespace_name': this.namespace,
              'deployment_name': this.data[index].name,
              'port': this.data[index].port
            }
            deploymentUpdate(params).then(res => {
              this.$Message.success({content:'更新成功!',duration: 5,closable: true})
            }).catch(err => {
              this.$Message.error({content:'更新失败!',duration: 5,closable: true})
            })
          },
          onCancel: () => {
            this.$Message.info('已取消更新');
          }
        })
      },
      // 回滚弹窗
      rollBack_view (index) {
        this.rollBackModal = true;
        this.$refs['formValidate'].resetFields();
        this.history_tag = [];
        this.formValidate.name = this.data[index].name;
        // this.deployment_port = this.data[index].port;
        var params = {
          'cloud_name': this.cloud_name,
          'namespace_name': this.namespace,
          'deployment_name': this.data[index].name
        }
        deploymentRollBackList(params).then(res => {
          var response = res.data
          for (const tag in response) {
            var select_data = {
              'value': response[tag]['tag'],
              'label': `发布时间：${response[tag]['update_time']} --- 镜像版本：${response[tag]['tag']}`
            }
            this.history_tag.push(select_data)
          }
        })
      },
      // 执行回滚
      rollBack (name) {
        this.$refs[name].validate((valid) => {
          if (valid) {
            // 请求后端接口进行回滚
            var params =  {
              'cloud_name': this.cloud_name,
              'namespace_name': this.namespace,
              'deployment_name': this.formValidate['name'],
              'tag': this.formValidate['version'],
              // 'port': this.deployment_port
            }
            deploymentRollBack(params).then(res => {
              this.$Message.success({content:'回滚成功!',duration: 5,closable: true})
            }).catch(err => {
              this.$Message.error({content:'回滚失败!',duration: 5,closable: true})
            })
          }
        })
      },
      // 修改
      updateEdit (index) {
        console.log(this.data[index].name)
      },
      // 删除
      remove (index) {
        this.$Modal.confirm({
          title: "警告!",
          content: `<p>删除${this.data[index].name}后会导致应用无法正常访问，是否继续？</p>`,
          onOk: () => {
            var params = {
              'cloud_name': this.cloud_name,
              'namespace_name': this.namespace,
              'deployment_name': this.data[index].name
            }
            deploymentDelete(params).then(res => {
              this.$Message.success({content:"删除成功！",duration: 5,closable: true})
            }).catch(err => {
              this.$Message.error({content:"删除失败！",duration: 5,closable: true})
            })
          },
          onCancel: () => {
            this.$Message.info('已取消删除');
          }
        })
      },
      // // 定时获取数据并重新加载页面
      cronGetDeployment () {
        this.cronGet = setInterval(() => this.deploymentData(true), 10000)
      }
    },
    created () {
      this.get_permission();
      // this.namespace_list();
      this.cronGetDeployment();
    },
    beforeDestroy () {
      // 退出当前页面时清除此定时请求任务
      clearInterval(this.cronGet)
    }
  }
</script>